# 新闻详情页:收藏//评论/点赞
from flask import render_template, session, current_app, abort, g, jsonify, request

from info import constants, db, response_code
from info.models import User, News, Comment, CommentLike
from info.modules.news import news_blue
from info.utils.comment import user_login_data

@news_blue.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():
    '''关注和取消关注'''

    #1.用户是否登录
    login_user = g.user
    if not login_user:
        return jsonify(errno=response_code.RET.SESSIONERR, errmsg='用户未登录')

    #2.接收参数
    user_id = request.json.get('user_id')
    action = request.json.get('action')


    #3效验参数
    if not all([user_id, action]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    if action not in ['follow', 'unfollow']:
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

    #4.查询是否存在
    try:
        other = User.query.get(user_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询用户失败')
    if not other:
        return jsonify(errno=response_code.RET.NODATA, errmsg='用户不存在')

    #5实现关注/取消关注
    if action == 'follow':
        if other not in login_user.followed:
            login_user.followed.append(other)
        else:
            return jsonify(errno=response_code.RET.DATAEXIST, errmsg='已关注')
    else:
        if other in login_user.followed:
            login_user.followed.remove(other)
        else:
            return jsonify(errno=response_code.RET.DATAEXIST, errmsg='未关注')

    #5同步到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='添加数据失败')
    # 8.响应结果
    return jsonify(errno=response_code.RET.OK, errmsg='OK')







@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    '''新闻点赞和取消点赞
    1.查询用户是否登录
    2.接收参数(comment_id,action)
    3.效验参数
    4.查询该评论信息是否存在
    5.查询该评论是否被点赞,
    6.没点赞则创建点赞模型类,点赞数加一,点赞了就删除点赞,点赞数减一
    7.同步到数据库
    8.响应点赞和取消点赞结果

    '''

    # 1.查询用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=response_code.RET.SESSIONERR, errmsg='用户未登录')
    # 2.接收参数
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')
    # 3.效验参数,并判断是否在action是否在add(点赞)，remove(取消点赞)
    if not all([comment_id, action]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    if action not in ['add', 'remove']:
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')
    # 4.查询该评论是否存在
    try:

        comment = Comment.query.filter(Comment.id == comment_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询评论数据失败')
    if not comment:
        return jsonify(errno=response_code.RET.NODATA, errmsg='评论数据不存在')
    # 5.查询该评论是否该用户被点赞
    try:
        comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id, CommentLike.user_id == user.id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询点赞数据失败')
    # 6.没点赞则创建点赞模型类,点赞数加一,点赞了就删除点赞,点赞数减一
    if action == 'add':
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id

            db.session.add(comment_like_model)
            # db.session.commit(comment_like_model)
#           累加点赞量
            comment.like_count += 1

    else:
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1

    # 7.添加到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='添加数据失败')
    # 8.响应结果
    return jsonify(errno=response_code.RET.OK, errmsg='OK')

@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    '''新闻评论及回复评论'''
    #     1.获取用户登录信息
    #     2.接收参数(news_id,comment,parent_id)
    #     3.效验参数
    #     4.查询新闻信息
    #   5.创建comment模型对象及对属性赋值
    #     6.响应结果
    #     1.获取用户信息
    user = g.user
    if not user:
        return jsonify(errno=response_code.RET.SESSIONERR, errmsg='用户未登录')
    # 2.接收参数
    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')
    # 3.判断参数是否在及参数id 是否是int
    if not all([news_id, comment_content]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')
    # 4.查询新闻信息是否存在
    try:

        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询新闻数据失败')
    if not news:
        return jsonify(errno=response_code.RET.NODATA, errmsg='新闻数据不存在')
    # 5.创建comment模型对象并对属性赋值
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content

    if parent_id:
        comment.parent_id = parent_id

    # 同步到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='评论失败')

    # 6.响应评论jieguo
    return jsonify(errno=response_code.RET.OK, data=comment.to_dict())


@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    '''新闻取消和收藏'''
    #     1.获取用户登录信息
    user = g.user
    if not user:
        return jsonify(errno=response_code.RET.SESSIONERR, errmsg='用户未登录')
    #     2.接收参数(news_id,action)
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    #     3.效验参数
    if not all([news_id, action]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')
    #     4.查询待收藏的新闻信息
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询新闻数据失败')
    if not news:
        return jsonify(errno=response_code.RET.NODATA, errmsg='新闻数据不存在')
    #     5.新闻收藏
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='操作失败')
    # 6.响应收藏
    return jsonify(errno=response_code.RET.OK, errmsg='收藏成功')


@news_blue.route('/detatil/<int:news_id>')
@user_login_data
def news_detatil(news_id):
    '''新闻详情页
    news_id,查询新的的id
    1.查询用户登录信息
    2.新闻地啊你排行
    3.新闻详情
    4.累积点击量
    5.收藏和取消收藏
    6.用户评论
    7.展示用户点的赞
    8.关注好取消关注

    '''
    # 1.查询用户登录信息
    # user_id = session.get('user_id', None)
    # user = None
    # if user_id:
    #     #     表示用户已经登录,查询用户信息
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    user = g.user

    # 2.新闻点击排行
    news_clicks = []
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 3.新闻详情
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        abort(404)

    # 4.累加点击量
    news.clicks += 1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    # 5.收藏和取消收藏

    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True

    # 6.用户评论
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()

    except Exception as e:
        current_app.logger.error(e)

    # 7.展示用户点过的赞
    # 查询用户点了哪些评论的赞
    comment_like_ids = []
    if user:
        try:
            comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id).all()
            # 取出所有被用户点赞的评论id
            comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger(e)


    # 因为模板渲染的数据,经过处理的,不想用模型类数据,而要把每个模型类转成字典

    comment_dict_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        # 给comment_dict追加一个is_like用于记录该评论是否被登录用户点赞了
        comment_dict['is_like'] = False
        if comment.id in comment_like_ids:
            comment_dict['is_like'] = True

        comment_dict_list.append(comment_dict)

    #8.关注和取消关注逻辑
    is_followed = False


    #用户已登录且用户看的新闻有作者
    if user and news.user:
        if news.user in user.followed:
            is_followed = True




    context = {
        'user': user.to_dict() if user else None,
        'news_clicks': news_clicks,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comments': comment_dict_list,
        'is_followed': is_followed
    }

    return render_template('news/detail.html', context=context)
